package com.example.impala.controller;

import com.cloudera.impala.jdbc41.internal.com.cloudera.altus.shaded.org.apache.commons.lang3.RandomStringUtils;
import com.example.impala.csv.CsvUtil;
import com.example.impala.jdbc.Jdbc;
import com.example.impala.model.ImpalaArg;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author: LiuJie
 * @Date: 2019-04-22 16:48
 * @Description:
 */
@RestController
@CrossOrigin
public class ImpalaApiController {

    @Autowired
    private Jdbc jdbc;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private CsvUtil csvUtil;

    @PostMapping("impala/sample")
    @ApiOperation("impala 测试")
    public ResponseEntity tryImpala(@Valid @RequestBody ImpalaArg arg) {
        List list = jdbc.findData(arg);
        return ResponseEntity.ok(list);
    }

    @PostMapping("impala/export")
    @ApiOperation("impala 导出")
    public byte[] export(@Valid @RequestBody ImpalaArg arg) throws UnsupportedEncodingException {
        String name = RandomStringUtils.randomAlphabetic(8);
        String fileName = URLEncoder.encode(name+".csv", "UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        byte[] fileByte = csvUtil.readFileByArg(arg);
        return fileByte;

    }
}
